import {
  Injectable,
  CanActivate,
  ExecutionContext,
  BadRequestException,
  NotFoundException,
} from '@nestjs/common';
import { Observable } from 'rxjs';

@Injectable()
export class CheckCpatchaGuard implements CanActivate {
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    const { captcha } = request.body;
    if (!request.session.captcha || !captcha) {
      throw new NotFoundException('验证码不能为空');
    }
    if (
      request.session.captcha.toLocaleLowerCase() !==
      captcha.toLocaleLowerCase()
    ) {
      throw new BadRequestException('验证码错误或已过期');
    }
    return true;
  }
}
